﻿using BackData;
using Domain.DTOs.RBAC;
using Domain.RBAC;
using Infratructure;
using MediatR;
using SqlSugar;
using Team.API.Applocation.Command.Users;

namespace Team.API.Applocation.Handler.Users
{
    public class QuseyUserHandler : IRequestHandler<QuseyUserCommand, APIPaging<UserDTO>>
    {
        private readonly IRepository<Usermodel> userRepository;
        private readonly IRepository<Rolemodel> roleRepository;
        private readonly IRepository<Departmentmodel> departmentRepository;

        public QuseyUserHandler(IRepository<Usermodel> userRepository,
            IRepository<Rolemodel> roleRepository,
            IRepository<Departmentmodel> departmentRepository)
        {
            this.userRepository = userRepository;
            this.roleRepository = roleRepository;
            this.departmentRepository = departmentRepository;
        }

        public async Task<APIPaging<UserDTO>> Handle(QuseyUserCommand request, CancellationToken cancellationToken)
        {
            int pageIndex = request.PageIndex <= 0 ? 1 : request.PageIndex;
            int pageSize = request.PageSize <= 0 ? 10 : request.PageSize;

            var userQuery = userRepository.GetAll()
                .Where(u => u.IsDel == false)
                .WhereIF(request.RoleId.HasValue, u => u.RoleId == request.RoleId!.Value)
                .WhereIF(request.DepartmentId.HasValue, u => u.DepartmentId == request.DepartmentId!.Value)
                .WhereIF(!string.IsNullOrWhiteSpace(request.Username), u => u.UserName.Contains(request.Username!.Trim()));

            var roleQuery = roleRepository.GetAll().Where(r => r.IsDel == false);
            var depQuery = departmentRepository.GetAll().Where(d => d.IsDel == false);

            var selectQuery = userQuery
                .InnerJoin(roleQuery, (u, r) => u.RoleId == r.Id)
                .InnerJoin(depQuery, (u, r, d) => u.DepartmentId == d.Id)
                .OrderBy((u, r, d) => u.Id, OrderByType.Desc)
                .Select((u, r, d) => new UserDTO
                {
                    Id = u.Id,
                    UserCode = u.UserCode,
                    UserName = u.UserName,
                    RealName = u.RealName,
                    RoleId = r.Id,
                    RoleName = r.RoleName,
                    DepartmentId = d.Id,
                    DepartmentName = d.DepartmentName,
                    Phone = u.Phone,
                    Email = u.Email
                });

            int totalCount = 0;
            var result = selectQuery.ToPageList(pageIndex, pageSize, ref totalCount);

            return new APIPaging<UserDTO>
            {
                Totalcount = totalCount,
                Code = StateCode.OK,
                Message = "获取用户列表成功",
                ListResult = result
            };
        }
    }
}
